package info.cs52.fes.ajax;

import info.cs52.fes.action.SessionUtils;
import info.cs52.fes.data.User;
import info.cs52.fes.lp.LanguageParser;
import info.cs52.fes.lp.NatureLanguageParser;
import info.cs52.fes.lp.PrologLanguageParser;
import info.cs52.fes.prolog.Engine;
import info.cs52.fes.prolog.TuPrologEngine;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class ChatHandle extends AjaxHandle {

	private final String[] RAN_MSG = {
			"Chào bạn, bạn khỏe chứ?",
			"Xin chào, Tôi có thể làm gì giúp bạn?",
			"Thời tiết hôm nay đẹp nhỉ, Hum nay cùng ăn một bữa thật ngon miệng nhé."
			};
	private PrologLanguageParser plp = new PrologLanguageParser();

	@Override	               
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String question = req.getParameter("question");
		if ("null".equals(question)) { 
			// TODO why "null"??? 
			question = null;
		}
		String userMessage = getUserMessage(req);
		String answer = userMessage;
		
		Engine engine = new TuPrologEngine();
		User user = SessionUtils.getUser(req);
		if (user.getKnowledgeBase() != null) {
			engine.setUserKnowledgeBase(user.getKnowledgeBase());
		}
		
		//gan type
		answer = getSimpleMessage(userMessage, Integer.parseInt(req.getParameter("type")));
		
		if (!StringUtils.isBlank(question) && !StringUtils.isBlank(answer)) {
			String term = engine.process(question, answer, plp.getCf());
			user.addKnowledge(term);
		}

		List<List<String>> recommendedMeals = engine.recommend();
		req.getSession().setAttribute("recommendedMeals", recommendedMeals);
		
		JsonObject ret = new JsonObject();
		ret.addProperty("user", getUserName(req) + ": " + userMessage/*StringEscapeUtils.escapeJavaScript(userMessage)*/);
		ret.addProperty("fesser", "Fesser: " + getFesserMsg(engine.getQuestion(), engine.getPrompt()));
		ret.addProperty("question", engine.getQuestion());
		ret.addProperty("type", ((TuPrologEngine)engine).getWaitingAnswerType());

		resp.setContentType("application/json");
		java.io.PrintWriter out = resp.getWriter();
		out.println(ret.toString());
	}

	private String getSimpleMessage(String userMessage, int type) {
		plp.setOriginalPhrase(userMessage);
		plp.setDefaultPattern(LanguageParser.ANSWER_PATTERNS);
		
		plp.setAnswerType(PrologLanguageParser.STRING);
		//answerType có 4 giá trị: YN=0, STRING=1, LIST=2, NUMBER=3 Cau hoi yeu cau tra ve cai j thì tra ve loai do
		plp.setAnswerType(type);
		plp.parse();
		return StringEscapeUtils.unescapeJavaScript(plp.getTranslatedPhrase());
	}
	
	protected String getFesserMsg(String question, String prompt) throws IOException{
		if (question == null) {
			return "Chúc bạn ngon miệng!";
		}
		return prompt;
	}
	
	protected String getUserName(HttpServletRequest req){
		//get later
		User user = SessionUtils.getUser(req);
		return user.getName();
	}
	
	protected String getUserMessage(HttpServletRequest req){
		String result = req.getParameter("user-msg").replace('\n', ' ').replaceAll(" +", " ").trim();
		//preprocess
		return StringEscapeUtils.unescapeJavaScript(result);
	}
}
